#
# core.py
#
# Copyright (C) 2009 Mark G. Whitney <markwhitney@gmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2009 Damien Churchill <damoxc@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge.    If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA  02110-1301, USA.
#
#    In addition, as a special exception, the copyright holders give
#    permission to link the code of portions of this program with the OpenSSL
#    library.
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version. If you delete this exception
#    statement from all source files in the program, then also delete it here.
#

import datetime
from deluge.log import LOG as log
from deluge.plugins.pluginbase import CorePluginBase
import deluge.component as component
import deluge.configmanager
from deluge.core.rpcserver import export
from collections import namedtuple
from twisted.internet.task import deferLater
from twisted.internet import reactor

DEFAULT_PREFS = {
    "stats_filename":"/tmp/stats.out",
    "report_interval":"day"
}

torrent_stats = {}

class TorrentStats():

    def __init__(self, name, hash_id, starting_payload_up, starting_payload_down):
        self.name = name
        self.hash_id = hash_id
        self.starting_payload_up = starting_payload_up
        self.starting_payload_down = starting_payload_down

    def compute_diff(self, new_payload_up, new_payload_down):
        UpDown = namedtuple("UpDown", "up down")
        return UpDown(new_payload_up - starting_payload_up, new_payload_down - starting_payload_down)

    def get_name(self):
        return self.name

class Core(CorePluginBase):
    def enable(self):
        self.config = deluge.configmanager.ConfigManager("transferstats.conf", DEFAULT_PREFS)
        self.schedule_next_update()

    def get_next_time(self, start_time, report_interval):
        """ Compute next time to update stats file

        """
        if report_interval == "day":
            next_time = start_time.replace(hour=0, minute=0, second=0, microsecond=0) + \
                        datetime.timedelta(days=1)
        elif report_interval == "hour":
            next_time = start_time.replace(minute=0, second=0, microsecond=0) + \
                        datetime.timedelta(hours=1)
        elif report_interval == "minute":
            next_time = start_time.replace(second=0, microsecond=0) + \
                        datetime.timedelta(minutes=1)
        return next_time

    def schedule_next_update(self):
        self.start_time = datetime.datetime.now()
        next_time = self.get_next_time(self.start_time, self.config["report_interval"])

        seconds_till = (next_time - self.start_time).total_seconds()
        log.debug("collecting stats in %d seconds" % (seconds_till))
        self.next_update = deferLater(reactor, seconds_till, self.update_stats)
        self.next_update.addErrback(lambda err: log.info("errback"))

    def update_stats(self, run_again=True):
        stats_fname = self.config["stats_filename"]
        log.info("writing stats to %s" % stats_fname)

        with open(stats_fname, "a") as f:
            f.write(self.generate_stats(component.get("Core")))

    def generate_stats(self, core_component, run_again=True):
        all_torrents = core_component.torrentmanager.torrents
        end_time = datetime.datetime.now()

        tor_dict = {}

        for tor_hash in all_torrents:
            name_dict = core_component.get_torrent_status(tor_hash, ["name", "tracker_host"])
            name = name_dict["name"]
            tracker = name_dict["tracker_host"]
            stat_dict = core_component.get_torrent_status(tor_hash, ["total_payload_upload",
                                                                     "total_payload_download"],
                                                          diff=True)
            log.debug(stat_dict)
            log.debug(name)
            if ("total_payload_upload" in stat_dict and stat_dict["total_payload_upload"] > 0) or \
                    ("total_payload_download" in stat_dict and stat_dict["total_payload_download"] > 0):
                tracker_stats = tor_dict.setdefault(tracker, {})
                tors = tracker_stats.setdefault("torrents", [])

                tor_stats = {}
                tor_stats["name"] = name
                tor_stats["upload"] = stat_dict["total_payload_upload"] / 1024.0
                tor_stats["download"] = stat_dict["total_payload_download"] / 1024.0

                tors.append(tor_stats)
                tracker_stats["upload"] = tracker_stats.setdefault("upload", 0) + tor_stats["upload"]
                tracker_stats["download"] = tracker_stats.setdefault("download", 0) + tor_stats["download"]

        out_lines = []

        out_lines.append("\n\nstart: %s, end: %s, %d hours\n" % \
                             (self.start_time,
                              end_time,
                              (end_time - self.start_time).total_seconds() / 60 / 60))

        for tracker in tor_dict:
            out_lines.append("\n%-43s %9.1f %9.1f\n" % (tracker,
                                                        tor_dict[tracker]["upload"] / 1024.0,
                                                        tor_dict[tracker]["download"] / 1024.0))

            for torrent in tor_dict[tracker]["torrents"]:
                out_lines.append("   %-40s %9.1f %9.1f\n" % (torrent["name"],
                                                             torrent["upload"] / 1024.0,
                                                             torrent["download"] / 1024.0))
        if run_again:
            self.schedule_next_update()

        return "".join(out_lines)


    def disable(self):
        self.update_stats(run_again=False)


    def update(self):
        all_torrents = component.get("Core").torrentmanager.torrents
        for tor_hash in all_torrents:
            log.debug(tor_hash)

    @export
    def set_config(self, config):
        """Sets the config dictionary"""
        for key in config.keys():
            self.config[key] = config[key]
        self.config.save()
        self.next_update.cancel()
        self.schedule_next_update()

    @export
    def get_config(self):
        """Returns the config dictionary"""
        return self.config.config
